import { _decorator, Component, Node, Animation } from 'cc';
import { TweenToStart } from '../../../scripts/libs/rxjs/cc3/TweenStart';
import { v3 } from 'cc';
import { AnimationPlay } from '../../../scripts/libs/rxjs/cc3/AnimationPlay';
import { Sprite } from 'cc';
import { concat } from 'rxjs';
import { Timer } from '../../../scripts/libs/rxjs/cc3/CreatorSchedule';
import { ResourceHelper } from '../../scripts/ResourceHelper';
import { instantFunc } from '../../../scripts/libs/rxjs/cc3/CommonObservable';
const { ccclass, property } = _decorator;

@ccclass('KeyFly')
export class KeyFly extends Component {

    @property(Node)
    mainNode: Node = null;

    reset() {
        this.node.clearSubscriptions();
        this.mainNode.setRotationFromEuler(0, 0, -45);
        let sprite = this.mainNode.getComponent(Sprite);
        sprite.spriteFrame = sprite.spriteAtlas.getSpriteFrame('keys_rot/01');
    }

    go() {
        this.node.clearSubscriptions();
        AnimationPlay(this.mainNode.getComponent(Animation), 'key_rot').subscribe().addTo(this.node);
        TweenToStart(this.mainNode, .3, { eulerAngles: v3(0, 0, 0) }).subscribe().addTo(this.node);
    }

    openKey(callback: () => void) {
        this.node.clearSubscriptions();
        concat(
            AnimationPlay(this.mainNode.getComponent(Animation), 'key_open_locker'),
            instantFunc(() => {
                if (callback) callback();
            }),
            Timer(.1, this.node),
        ).subscribe({
            complete: () => {
                this.node.clearSubscriptions();
                ResourceHelper.KeyFlyPool.putNode(this.node);
            }
        }).addTo(this.node);

    }
}

